const PDFMerger = require('pdf-merger-js');
const util = require('./util');
const path = require('path');
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
const fse = require('fs-extra');
const fs = require('fs');
const pdfParse = require('pdf-parse');
const download = require('download');
const emptyPdf = path.join(__dirname, './empty.pdf');
const HttpRe = /^https?:\/\//;
const profile = require('../profile')
const REGION = profile.REGION;
const bucketName = profile.bucketName;
const fileS3Path = profile.fileS3Path;



/**
 * pdf 文件合并
 * @param pdfPaths
 * @param oddPageAutoInsertBlank
 * @param basePath
 * @return {Promise<string>}
 */
exports.mergesPdf = async function ({pdfPaths, oddPageAutoInsertBlank}, basePath) {

    const contents = [];
    const bufferCache = {};
    const parseCache = {};

    for (const uri of pdfPaths) {
        if (uri) {
            let buffer;
            if (bufferCache[uri]) {
                buffer = bufferCache[uri];
            } else {
                buffer = await getPdfBuffer(uri, basePath);
            }

            bufferCache[uri] = buffer;

            let parse = parseCache[uri];
            if (!parse) {
                try {
                    parse = parseCache[uri] = await pdfParse(buffer);
                } catch (e) {
                    throw `【pdf-parse】文件解析失败，请检查文件内容是否正确 ${uri}`;
                }
            }

            contents.push(buffer);

            if (oddPageAutoInsertBlank) { // 自动根据是否单页补充一个空白页（用来支持双面打印）
                if (parse.numpages % 2) {// 如果页数是单数，补充一个空白页
                    contents.push(emptyPdf);
                }
            }
        } else {
            contents.push(emptyPdf);
        }
    }

    const filePath = '/' + util.generatePath();
    const outputFilePath = path.join(util.generateBasePath, filePath)
    const logs = [];
    tickLog('util.generateBasePath', util.generateBasePath);
    tickLog('filePath', filePath);
    tickLog('outputFilePath', outputFilePath);

    try {
        const merger = new PDFMerger();
        contents.forEach(file => merger.add(file));
        fse.ensureDirSync(path.dirname(outputFilePath)); // 创建目录
        await merger.save(outputFilePath);

        //上传S3  /root/pdf-service-generate/2021-7-8/1625729018830.pdf
        // const REGION = "cn-northwest-1";
        // Set the bucket parameters
        // const bucketName = "iplus-aws-test-bucket";
        // const fileS3Path = 'filesvr/pdf-generate/';

        const key = fileS3Path + filePath;

        tickLog('s3路径', key);
        const objectParams = { Bucket: bucketName, Key: key, Body: fs.createReadStream(outputFilePath) };
        const s3 = new S3Client({ region: REGION });
        const run = async () => {
            try {
                const results = await s3.send(new PutObjectCommand(objectParams));
                console.log("Successfully uploaded data to " + bucketName + key );
            } catch (err) {
                console.log("Error", err);
            }
        };
        await run();


    } catch (e) {
        tickErrLog('Error：', String(e.message || e));
        throw e;
    } finally {
        flushLog();
    }

    return filePath;

    function tickLog(...args) {
        logs.push(args);
    }

    function tickErrLog(...args) {
        const log = [...args];
        log.method = 'error';
        logs.push(log);
    }

    function flushLog() {
        const label = '【merge-pdf】';
        console.log('')
        console.log('')
        console.log('Start');
        console.log('  ', 'files', pdfPaths);
        logs.forEach(log => console[log.method || 'log']('  ', ...log));
        console.log('End');
        console.log('');
    }
};

/**
 * pdf 文件拆分
 * @param pdfPath
 * @param basePath
 * @return {Promise<[]>}
 */
exports.splitsPdf = async function ({pdfPath}, basePath) {
    const buffer = await getPdfBuffer(pdfPath, basePath);
    const {numpages} = await pdfParse(buffer);

    const paths = [];
    for (let i = 0; i < numpages; i++) {
        const merger = new PDFMerger();
        merger.add(buffer, [i + 1]);

        const filePath = util.generatePath();
        const outputFilePath = path.join(util.generateBasePath, filePath)
        fse.ensureDirSync(path.dirname(outputFilePath));
        await merger.save(outputFilePath);
        paths.push(filePath);
    }
    return paths;
}

async function getPdfBuffer(uri, basePath) {
    if (HttpRe.test(uri)) {
        return download(uri);
    } else if (uri.startsWith('/')) {
        const absPath = getAbsPath(uri, basePath);
        if (!fs.existsSync(absPath)) {
            throw `无法合并PDF，未找到文件【${uri}】`;
        }
        return fs.readFileSync(absPath);
    } else {
        throw `【${uri}】文件路径错误，仅支持合并 http 开头的远程文件或者 ${basePath} 开头的文件`;
    }
}

function getAbsPath(filePath, basePath) {
    if (filePath.startsWith(basePath)) {
        filePath = filePath.replace(basePath, '');
    }
    return path.join(util.generateBasePath, filePath);
}
